package com.h3bpm.starcharge.common.uitl;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.h3bpm.starcharge.common.bean.WorkFlowUniversalParam;
import com.h3bpm.starcharge.common.bean.WorkFlowZbParam;

import java.util.ArrayList;
import java.util.List;

/**
 * Scit参数处理工具
 *
 * @author LLongAgo
 * @date 2019/2/22
 * @since 1.0.0
 */
public class ScitParamUtil {

    // 转换普通参数
    public static String paramToJson(String param) {
        //Json的解析类对象
        JsonParser parser = new JsonParser();
        //将JSON的String 转成一个JsonArray对象
        JsonArray jsonArray = parser.parse(param).getAsJsonArray();

        Gson gson = new Gson();
        ArrayList<WorkFlowUniversalParam> params = new ArrayList<>();
        for (JsonElement user : jsonArray) {
            //使用GSON，直接转成Bean对象
            WorkFlowUniversalParam universalParam = gson.fromJson(user, WorkFlowUniversalParam.class);
            params.add(universalParam);
        }
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        for (WorkFlowUniversalParam w : params) {
            sb.append("\"").append(w.getName()).append("\":");
            sb.append("\"").append(w.getValue()).append("\",");
        }
        sb.deleteCharAt(sb.length() - 1).append("}");
        return sb.toString();
    }

    // 转换子表参数
    public static String zbParamToJson(String jsonStr) {
        JsonParser parser = new JsonParser();
        //将JSON的String 转成一个JsonArray对象
        JsonArray jsonArray = parser.parse(jsonStr).getAsJsonArray();
        Gson gson = new Gson();
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        for (JsonElement user : jsonArray) {
            //使用GSON，直接转成Bean对象
            WorkFlowZbParam zbValue = gson.fromJson(user, WorkFlowZbParam.class);
            sb.append("\"").append(zbValue.getName()).append("\":");
            sb.append("[");
            List<List<WorkFlowZbParam.ValueBean>> values = zbValue.getValue();
            for (List<WorkFlowZbParam.ValueBean> value : values) {
                sb.append("{");
                for (WorkFlowZbParam.ValueBean v : value) {
                    sb.append("\"").append(v.getName()).append("\":");
                    sb.append("\"").append(v.getValue()).append("\",");
                }
                sb.deleteCharAt(sb.length() - 1).append("}").append(",");
            }
            sb.deleteCharAt(sb.length() - 1).append("]");
            sb.append(",");
        }
        sb.deleteCharAt(sb.length() - 1).append("}");
        return sb.toString();
    }

}